#include "widget.h"
#include "ui_widget.h"
#include "QLineEdit"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    tim.setInterval(33);
    imag=new QImage(); //初始化

    int flag=0;

luru_i=(ui->lineEdit->text()).toInt();
name=(ui->lineEdit_2->text()).toStdString();//获取姓名


    facedector.load("/home/lyx/shixun/opencv_now/haarcascade_frontalface_alt2.xml");
    eyedector.load("/home/lyx/shixun/opencv_now//haarcascade_eye_tree_eyeglasses.xml");
    model=  LBPHFaceRecognizer::create(); //创建学习模型就是LBPH


    //信号与槽
    connect(&tim,SIGNAL(timeout()),this,SLOT(time_out()));
    connect(ui->open, SIGNAL(clicked()), this, SLOT(openCamara())); //打开摄像头
    connect(ui->pic, SIGNAL(clicked()), this, SLOT(takingPicture())); //照相
    connect(ui->closeCam, SIGNAL(clicked()), this, SLOT(closeCamara())); //关闭摄像头
    connect(ui->xun,SIGNAL(clicked()), this, SLOT(renlianxunlian())); //人脸训练
    connect(ui->exit,SIGNAL(clicked()), this, SLOT(closed())); //退出
    connect(ui->in,SIGNAL(clicked()), this, SLOT(luru())); //录入信息


}

Widget::~Widget()
{
    delete ui;
}

//打开摄像头
void Widget::openCamara(){
    if(ui->open->text()=="开始")
      {
          cap.open(-1);
          cap.set(CAP_PROP_FRAME_WIDTH, 640.0);//设置摄像头采集图像分辨率
          cap.set(CAP_PROP_FRAME_HEIGHT, 480.0);


          ui->open->setText("结束");
          tim.start();
      }else
      {
          cap.release();

          ui->open->setText("开始");
           tim.stop();
      }

}


//拍照
void Widget::takingPicture(){
    Mat cun;
    cap.read(cun);

    imwrite("/home/lyx/shixun/camaraphoto/1.jpg",cun);
    //需要得到打cvimg转化成 Label能显示的QImage
          QImage qimg = Mat2QImage(cun);
          //直接把 qimag放到 QLabel中显示了！

          ui->label->setPixmap(QPixmap::fromImage(qimg));

}

//关闭摄像头
void Widget::closeCamara(){
    cap.release();
    tim.stop();

}

//人脸训练
void Widget::renlianxunlian(){

luru_i=(ui->lineEdit->text()).toInt();
    for(int i=0;i<3;i++)
    {
        Mat srcimg =imread(format("/home/lyx/shixun/renlian%d/myface_%d.jpg",luru_i,i));
        cvtColor(srcimg,srcimg,CV_BGR2GRAY);//转换为灰度图片
        study_faces.push_back(srcimg);//压栈--往里面填充数据！
        study_index.push_back(luru_i);//17就相当我这张人脸的索引号


    }
    study_faces.pop_back();
    study_index.pop_back();
    model->train(study_faces,study_index);
        //我们通过容器进行训练
        //训练需要图片！
    ft2 = freetype::createFreeType2();//初始化中文容器
    ft2->loadFontData("/usr/share/fonts/truetype/arphic/uming.ttc",0);
 qDebug()<<"训练成功";

}


//人脸识别
void Widget::time_out()
{

    int flag=0;
    Mat cvimg;
    cap.read(cvimg);
luru_i=(ui->lineEdit->text()).toInt();
name=(ui->lineEdit_2->text()).toStdString();//获取姓名


      Mat tmpimg;//OpenCV专用的数据！
        vector<Rect> faces;
       //vector<Rect> eyes;
        //flip(cvimg,cvimg,1);
            cvtColor(cvimg,tmpimg,CV_BGR2GRAY);//灰度处理
            equalizeHist(tmpimg,tmpimg);
            facedector.detectMultiScale(tmpimg,faces,1.1,15,0,Size(10,10),Size(640,480));
           // eyedector.detectMultiScale(tmpimg,eyes,1.1,15,0,Size(1,1),Size(640,480));

            if(faces.size()>0)
               {
                   for(int i =0;i<faces.size();i++)
                   {
                       static int count = 0;
                       Mat dst;//存储人脸的Mat类型数据

                       if(count<=10)
                       {
                           cv::resize(cvimg(faces[i]),dst,Size(100,100));
                           //得到了dst图片--仅仅存储着人脸
                           //人脸数据就是 100*100
                           //imwrite(format("/home/lyx/shixun/pairen/myface_%d.jpg",count),dst);
                       }
                       count++;

                       //识别当前的脸是否为你之前训练的人脸
                       Mat tmpface ;
                       int predictLabel = -1;
                       double predictConfidence = 0.0;
                       cv::resize(tmpimg(faces[i]),tmpface,Size(100,100));
                       model->predict(tmpface,predictLabel,predictConfidence);

                       for (int j=0;j<renshu;j++ ) {
                       if(predictLabel==shenfenzu[j].shenfen_index&&predictConfidence<100)
                       {

                                 flag=1;
                                 ft2->putText(cvimg,shenfenzu[j].shenfen_name,faces[i].tl(),40,Scalar(0,0,255),-1,8,true);

                                 qDebug()<<"predictLabel=="<<predictLabel<<"predictConfidence=="<<predictConfidence;

                       }
//                       else
//                       {
//                            if(flag==0)
//                            {
//                               ft2->putText(cvimg,"非法入侵",faces[i].tl(),40,Scalar(0,0,255),-1,8,true);
//                            }
//                       }
                       }



                        rectangle(cvimg,faces[i],Scalar(0,0,255),2,16);
                        //rectangle(cvimg,faces[0],Scalar(0,0,255),2,16);//0只是一个脸
                   }
            }



//     if(eyes.size()>0)
//         {
//             for(int i =0;i<eyes.size();i++)
//             {
//                 rectangle(cvimg,eyes[i],Scalar(255,0,255),2,16);
//             }
//         }

            //需要得到打cvimg转化成 Label能显示的QImage
              QImage qimg = Mat2QImage(cvimg);
              //直接把 qimag放到 QLabel中显示了！
     ui->label_2->setPixmap(QPixmap::fromImage(qimg));

}

void Widget::luru()
{

    Mat cvimg;
    cap.read(cvimg);
luru_i=(ui->lineEdit->text()).toInt();
name=(ui->lineEdit_2->text()).toStdString();//获取姓名
      Mat tmpimg;//OpenCV专用的数据！
        vector<Rect> faces;
       //vector<Rect> eyes;
        //flip(cvimg,cvimg,1);
            cvtColor(cvimg,tmpimg,CV_BGR2GRAY);//灰度处理
            equalizeHist(tmpimg,tmpimg);
            facedector.detectMultiScale(tmpimg,faces,1.1,15,0,Size(10,10),Size(640,480));


            if(faces.size()>0)
               {
                   for(int i =0;i<faces.size();i++)
                   {
                       static int count = 0;
                       Mat dst;//存储人脸的Mat类型数据

                       while(count<=10)
                       {
                           cv::resize(cvimg(faces[i]),dst,Size(100,100));
                           //得到了dst图片--仅仅存储着人脸
                           //人脸数据就是 100*100
                           imwrite(format("/home/lyx/shixun/renlian%d/myface_%d.jpg",luru_i,count),dst);
                           count++;
                       }
                       count=0;
                       ui->in->setText("录入完成");
                         shenfenzu[renshu].shenfen_index=luru_i;
                          shenfenzu[renshu].shenfen_name=name;
                          renshu++;
                          waitKey(300);
              ui->in->setText("信息录入");

                   }
            }

}

//退出程序
void Widget::closed(){
exit(0);
}

//类型转换
QImage Widget::Mat2QImage(cv::Mat cvImg)
{
    QImage qImg;
    cv::cvtColor(cvImg,cvImg,CV_BGR2RGB);
    //cv::cvtColor(cvImg,cvImg,cv::COLOR_BGR2RGB);
    qImg=QImage((const unsigned char*)(cvImg.data),
                             cvImg.cols,cvImg.rows,          //宽，高
                             cvImg.step,                     //步长
                             QImage::Format_RGB888);         //24位图，RGB=[0,1,2]
    //return qImg.rgbSwapped();
    return qImg;
}
